package com.atguigu.lease.common.handler;

import com.atguigu.lease.common.consts.StgyAdminConstant;
import com.atguigu.lease.common.util.JwtUtil;
import com.atguigu.lease.model.bean.SystemUser;
import com.atguigu.lease.model.bean.UserInfo;
import io.jsonwebtoken.impl.DefaultClaims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

//拦截器必须注册拦截地址，否则不生效！！！！！
@Component
public class StgyAppAuthInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<UserInfo> APP_USER_THREAD_LOCAL = new ThreadLocal<>();
    //handler方法执行前拦截请求  返回true表示放行  false拦截请求
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //放行预检请求
        if(request.getMethod().toUpperCase()
                .equals(RequestMethod.OPTIONS.name())) {
            return true;
        }


        //获取请求报文中的ACCESS_TOKEN 进行校验
        String token = request.getHeader("ACCESS_TOKEN");
        DefaultClaims claims = JwtUtil.parseToken(token);//解析时 如果token解析失败 直接抛出异常，后面的代码不会执行了
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(claims.get(StgyAdminConstant.JWT_TOKEN_USER_NAME, String.class));
        userInfo.setAvatarUrl(claims.get(StgyAdminConstant.JWT_TOKEN_AVATAR_URL, String.class));
        userInfo.setId(Long.parseLong(claims.get(StgyAdminConstant.JWT_TOKEN_USER_ID, String.class)));
        APP_USER_THREAD_LOCAL.set(userInfo);
        //放行： token存在并且解析成功
        return true;
    }
    //防止内存泄漏：
    //handler方法调用完毕后 才会执行，可以进行收尾操作：删除线程对象缓存的数据
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        APP_USER_THREAD_LOCAL.remove();
    }
}
